package com.gomore.opple.module.main.good;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gomore.opple.R;
import com.gomore.opple.common.GlobalConstant;
import com.gomore.opple.model.EventIsExpend;
import com.gomore.opple.model.EventKeySearch;
import com.gomore.opple.model.EventScanCode;
import com.gomore.opple.model.Filter;
import com.gomore.opple.model.QueryFilter;
import com.gomore.opple.model.ReflahEvent;
import com.gomore.opple.model.SecondFilter;
import com.gomore.opple.module.BaseFragmentV4;
import com.gomore.opple.module.IntentStart;
import com.gomore.opple.module.main.good.adapter.GoodAdapter;
import com.gomore.opple.module.main.good.adapter.PopRecyclerViewAdapter;
import com.gomore.opple.module.main.good.adapter.TypeNameAdapter;
import com.gomore.opple.rest.shopcart.SaveShoppingCartRequest;
import com.gomore.opple.service.AddtoShoppingCarListener;
import com.gomore.opple.utils.DensityUtil;
import com.gomore.opple.utils.DialogUtils;
import com.gomore.opple.widgets.MyGridView;
import com.gomore.opple.widgets.PullBaseView;
import com.gomore.opple.widgets.PullRecyclerView;
import com.gomore.opple.widgets.adapter.MultiItemTypeAdapter;
import com.gomore.opple.widgets.dialog.ConfirmDialog;
import com.unnamed.b.atv.model.TreeNode;
import com.unnamed.b.atv.view.AndroidTreeView;

import org.w3c.dom.Text;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

/**
 * Created by asus on 2017/5/9.
 */
public class GoodFragment extends BaseFragmentV4 implements GoodContract.View,
        PullBaseView.OnRefreshListener, AddtoShoppingCarListener {

    @Bind(R.id.shellLayout)
    RelativeLayout shellLayout;
    @Bind(R.id.carImage)
    ImageView carImage;
    @Bind(R.id.search_text)
    TextView search_text;
    @Bind(R.id.scan)
    ImageView scan;
    @Bind(R.id.filter)
    LinearLayout filter;
    @Bind(R.id.filter_my_grid_view)
    MyGridView filter_my_grid_view;
    @Bind(R.id.recyclerView)
    PullRecyclerView recyclerView;
    @Bind(R.id.empty_view)
    View empty_view;
    @Bind(R.id.view)
    View lineView;
    private GoodContract.Presenter mPresenter;
    private GoodAdapter goodAdapter;
    private PopRecyclerViewAdapter popRecyclerViewAdapter;
    private PopupWindow popupWindow;
    private TypeNameAdapter typeNameAdapter;
    private List<String> filterTypeNameList;
    private QueryFilter queryFilter;
    //动画
    private float[] mCurrentPosition = new float[2];
    private PathMeasure mPathMeasure;

    public static GoodFragment getInstance() {
        return new GoodFragment();
    }

    @Override
    protected void initalizeData() {
        super.initalizeData();
        EventBus.getDefault().register(this);
        filterTypeNameList = new ArrayList<>();
        queryFilter = new QueryFilter();
        mPresenter.queryGoods(queryFilter, false, true);
    }

    @Override
    protected void initalizeViews() {
        super.initalizeViews();
        //筛选条件
        typeNameAdapter = new TypeNameAdapter(getActivity(), filterTypeNameList);
        filter_my_grid_view.setAdapter(typeNameAdapter);
        //商品
        goodAdapter = new GoodAdapter(getActivity(), getActivity(), R.layout.item_goods, mPresenter.getData());
        recyclerView.setLayoutManager(new GridLayoutManager(GoodFragment.this.getActivity(), 2));
        recyclerView.setAdapter(goodAdapter);
        recyclerView.setOnRefreshListener(this);
        goodAdapter.setAddtoShoppingCarListener(this);
        goodAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                IntentStart.getInstance().startGoodDetailActivity(getActivity(), mPresenter.getData().get(position).getId());
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

    }

    @Override
    protected int getLayoutView() {
        return R.layout.fragment_good;
    }

    @Override
    public void showProgressDialog() {
        DialogUtils.showLoadingDialog(getActivity(), getResources().getString(R.string.loading));
    }

    @Override
    public void hideProgressDialog() {
        DialogUtils.closeLoadingDialog();
    }

    @Override
    public void showMessage(String msg) {
        showToast(msg);
    }

    @Override
    public void showMessage(int msgId) {
        showToast(msgId);
    }


    @Override
    public void showLoadMoreCompleted() {
        recyclerView.onFooterRefreshComplete();
    }

    @Override
    public void showRefreshCompleted() {
        recyclerView.onHeaderRefreshComplete();
    }

    @Override
    public void showContent() {
        goodAdapter.notifyDataSetChanged();
        if (mPresenter.getData().size() == 0) {
            recyclerView.setVisibility(View.GONE);
            empty_view.setVisibility(View.VISIBLE);
        } else {
            recyclerView.setVisibility(View.VISIBLE);
            empty_view.setVisibility(View.GONE);
        }
    }

    @Override
    public void goGoodDetail(String goodUuid) {
        IntentStart.getInstance().startGoodDetailActivity(getActivity(), goodUuid);
    }

    @Override
    public void setPresenter(GoodContract.Presenter presenter) {
        mPresenter = presenter;
    }

    @Override
    public void onHeaderRefresh(PullBaseView view) {
        mPresenter.queryGoods(queryFilter, false, false);
    }

    @Override
    public void onFooterRefresh(PullBaseView view) {
        mPresenter.queryGoods(queryFilter, true, false);
    }

    @OnClick({R.id.search_text, R.id.scan, R.id.filter})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.search_text:
                IntentStart.getInstance().startSearchGoodsActivity(getActivity(), search_text.getText().toString().trim());
                break;
            case R.id.scan:
                IntentStart.getInstance().startMipcaActivityCaptureActivity(getActivity(), GlobalConstant.FragmentType.GOODFRAGMENT);
                break;
            case R.id.filter:
                showFilterView(mPresenter.getFilter());
                break;
        }
    }

    //展示筛选框
    public void showFilterView(List<Filter> filters) {
        LayoutInflater inflater = LayoutInflater.from(getActivity());
        View view = inflater.inflate(R.layout.slide_menu, null);
        LinearLayout slide = (LinearLayout) view.findViewById(R.id.slide);
        PullRecyclerView popRecyclerView = (PullRecyclerView) view.findViewById(R.id.pop_recyclerView);
        TextView reset = (TextView) view.findViewById(R.id.reset);
        TextView confirm = (TextView) view.findViewById(R.id.confirm);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
        popRecyclerView.setLayoutManager(layoutManager);
        popRecyclerViewAdapter = new PopRecyclerViewAdapter(getActivity(), R.layout.pop_recycler_view_item, filters);
        popRecyclerView.setAdapter(popRecyclerViewAdapter);
        popRecyclerView.setCanPullDown(false);
        popRecyclerView.setCanPullUp(false);
        //自适配长、框设置
        popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        //设置popWindow的显示和消失动画
        popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
        popupWindow.update();
        popupWindow.setTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.showAsDropDown(lineView, 0, 0);
        slide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        reset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                resetData();
            }
        });

        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //判断是否选中条件
//                if (!hasData()) {
//                    showMessage(R.string.select_filter);
//                    return;
//                }
                List<SecondFilter> secondFilters = getData();
                getTypeNameAndCode(secondFilters);
                popupWindow.dismiss();
                typeNameAdapter.notifyDataSetChanged();
                mPresenter.queryGoods(queryFilter, false, false);
            }
        });
    }

    //控制选择分类只选一个
    public void onEventMainThread(SecondFilter secondFilter) {
        if (secondFilter != null && secondFilter.getTypeCode() != null) {
            for (int i = 0; i < mPresenter.getFilter().size(); i++) {
                if (!mPresenter.getFilter().get(i).isFirstCategory()) {
                    for (int j = 0; j < mPresenter.getFilter().get(i).getSecondFilterList().size(); j++) {
                        if (!secondFilter.getTypeCode().equals
                                (mPresenter.getFilter().get(i).getSecondFilterList().get(j).getTypeCode())) {
                            mPresenter.getFilter().get(i).getSecondFilterList().get(j).setIsSelect(false);
                        }
                    }
                }
            }
            popRecyclerViewAdapter.notifyDataSetChanged();
        }
    }

    //控制分类展开，收缩
    public void onEventMainThread(EventIsExpend eventIsExpend) {
        if (eventIsExpend != null) {
            for (int i = 0; i < mPresenter.getFilter().size(); i++) {
                if (!mPresenter.getFilter().get(i).isFirstCategory()) {
                    mPresenter.getFilter().get(i).setIsExpend(eventIsExpend.isExpend());
                }
            }
        }
        popRecyclerViewAdapter.notifyDataSetChanged();
    }

    //搜索界面传过来
    public void onEventMainThread(EventKeySearch eventKeySearch) {
        if (eventKeySearch != null) {
            if (TextUtils.isEmpty(eventKeySearch.getKey())) {
                queryFilter.setNameLike(null);
                search_text.setText("");
            } else {
                queryFilter.setNameLike(eventKeySearch.getKey());
                search_text.setText(eventKeySearch.getKey());
            }
            mPresenter.queryGoods(queryFilter, false, false);
        }
    }

    //扫码
    public void onEventMainThread(EventScanCode eventScanCode) {
        if (eventScanCode != null && eventScanCode.getCode() != null
                && eventScanCode.getFragmentType().equals(GlobalConstant.FragmentType.GOODFRAGMENT)) {
            mPresenter.getGoodByBarCode(eventScanCode.getCode());
        }
    }

    //是否选中筛选条件
    private boolean hasData() {
        boolean hasData = false;
        for (int i = 0; i < mPresenter.getFilter().size(); i++) {
            for (int j = 0; j < mPresenter.getFilter().get(i).getSecondFilterList().size(); j++) {
                if (mPresenter.getFilter().get(i).getSecondFilterList().get(j).isSelect()) {
                    hasData = true;
                    break;
                }
            }
            if (hasData == true) {
                break;
            }
        }
        return hasData;
    }

    //重置筛选
    private void resetData() {
        //所有条件置为未选
        for (int i = 0; i < mPresenter.getFilter().size(); i++) {
            for (int j = 0; j < mPresenter.getFilter().get(i).getSecondFilterList().size(); j++) {
                mPresenter.getFilter().get(i).getSecondFilterList().get(j).setIsSelect(false);
            }
        }
        popRecyclerViewAdapter.notifyDataSetChanged();
        //筛选typeName置为空
        filterTypeNameList.clear();
        typeNameAdapter.notifyDataSetChanged();
        filter_my_grid_view.setVisibility(View.GONE);
        //查询条件置为空
        resetQueryFilter();
        mPresenter.queryGoods(queryFilter, false, false);
    }

    //筛选条件确定
    private List<SecondFilter> getData() {
        List<SecondFilter> secondFilterList = new ArrayList<>();
        for (int i = 0; i < mPresenter.getFilter().size(); i++) {
            for (int j = 0; j < mPresenter.getFilter().get(i).getSecondFilterList().size(); j++) {
                if (mPresenter.getFilter().get(i).getSecondFilterList().get(j).isSelect()) {
                    secondFilterList.add(mPresenter.getFilter().get(i).getSecondFilterList().get(j));
                }
            }
        }
        return secondFilterList;
    }

    //得到筛选字段
    private void getTypeNameAndCode(List<SecondFilter> secondFilterList) {
        //先清除数据
        filterTypeNameList.clear();
        resetQueryFilter();
        for (int i = 0; i < secondFilterList.size(); i++) {
            if (secondFilterList.get(i).getCategory().equals(GlobalConstant.FilterCategory.STYLES)) {
                queryFilter.setStyleEquals(secondFilterList.get(i).getTypeCode());
            }
            if (secondFilterList.get(i).getCategory().equals(GlobalConstant.FilterCategory.CATEGORIES)) {
                queryFilter.setCategoryEquals(secondFilterList.get(i).getTypeCode());
            }
            if (secondFilterList.get(i).getCategory().equals(GlobalConstant.FilterCategory.SPACE)) {
                queryFilter.setSpaceEquals(secondFilterList.get(i).getTypeCode());
            }
            if (secondFilterList.get(i).getCategory().equals(GlobalConstant.FilterCategory.MATERIAL)) {
                queryFilter.setMaterialEqueals(secondFilterList.get(i).getTypeCode());
            }
            if (secondFilterList.get(i).getCategory().equals(GlobalConstant.FilterCategory.PRICE)) {
                String[] priceArray = secondFilterList.get(i).getTypeName().split("到");
                BigDecimal stratPrice = new BigDecimal(priceArray[0].trim());
                BigDecimal endPrice = new BigDecimal(priceArray[1].trim());
                queryFilter.setStartprice(stratPrice);
                queryFilter.setEndprice(endPrice);
            }
            filterTypeNameList.add(secondFilterList.get(i).getTypeName());
        }
        if (filterTypeNameList.size() > 0) {
            filter_my_grid_view.setVisibility(View.VISIBLE);
        }
    }

    //    将查询条件置为空
    private void resetQueryFilter() {
        queryFilter.setStyleEquals(null);
        queryFilter.setCategoryEquals(null);
        queryFilter.setSpaceEquals(null);
        queryFilter.setMaterialEqueals(null);
        queryFilter.setStartprice(null);
        queryFilter.setEndprice(null);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void addToShoppingCar(String goodsId, ImageView imageView) {
        if (goodsId != null) {
            if (mPresenter.getConsumer() == null) {
                showMessage(getActivity().getResources().getString(R.string.select_consumetr));
                return;
            }
            //开始动画
            addToCarAnimation(goodsId, imageView);
        }
    }

    private void addToCarAnimation(final String goodsId, ImageView goodsImg) {
        //获取需要进行动画的ImageView
        final ImageView animImg = new ImageView(getActivity());
        animImg.setImageDrawable(goodsImg.getDrawable());
        //图片初始化大小
        int screenWidth = DensityUtil.screenWith(getActivity());
        int width = (screenWidth - DensityUtil.dip2px(getActivity(), 10 + 12 + 12)) / 2;
        int height = (width * 13) / 17;
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(width, height);
        shellLayout.addView(animImg, params);
        //设置位置
        final int shellLocation[] = new int[2];
        shellLayout.getLocationInWindow(shellLocation);
        int animImgLocation[] = new int[2];
        goodsImg.getLocationInWindow(animImgLocation);
        int carLocation[] = new int[2];
        carImage.getLocationInWindow(carLocation);

        // 起始点：图片起始点-父布局起始点+该商品图片的一半-图片的marginTop || marginLeft 的值
        float startX = animImgLocation[0] - shellLocation[0] + goodsImg.getWidth() / 2 - DensityUtil.dip2px(getActivity(), 10.0f);
        float startY = animImgLocation[1] - shellLocation[1] + goodsImg.getHeight() / 2 - DensityUtil.dip2px(getActivity(), 10.0f);

        // 商品掉落后的终点坐标：购物车起始点-父布局起始点-购物车图片的1/4
        float endX = carLocation[0] - shellLocation[0] - carImage.getWidth() / 4;
        float endY = carLocation[1] - shellLocation[1];

        //控制点，控制贝塞尔曲线
        float ctrlX = (startX + endX) / 2;
        float ctrlY = startY - 100;

        Log.e("num", "-------->" + ctrlX + " " + startY + " " + ctrlY + " " + endY);

        Path path = new Path();
        path.moveTo(startX, startY);
        //使用二阶贝塞尔曲线
        path.quadTo(ctrlX, ctrlY, endX, endY);
        mPathMeasure = new PathMeasure(path, false);
        //缩放动画
        ObjectAnimator scaleXanim = ObjectAnimator.ofFloat(animImg, "scaleX", 1, 0.7f, 0.5f, 0.3f, 0.1f);
        ObjectAnimator scaleYanim = ObjectAnimator.ofFloat(animImg, "scaleY", 1, 0.7f, 0.5f, 0.3f, 0.1f);
        //位移动画
        ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, mPathMeasure.getLength());
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                // 这里这个值是中间过程中的曲线长度（下面根据这个值来得出中间点的坐标值）
                float value = (Float) animation.getAnimatedValue();
                // 获取当前点坐标封装到mCurrentPosition
                // 传入一个距离distance(0<=distance<=getLength())，然后会计算当前距离的坐标点和切线，
                // pos会自动填充上坐标，这个方法很重要。
                // mCurrentPosition此时就是中间距离点的坐标值
                mPathMeasure.getPosTan(value, mCurrentPosition, null);
                // 移动的商品图片（动画图片）的坐标设置为该中间点的坐标
                animImg.setTranslationX(mCurrentPosition[0]);
                animImg.setTranslationY(mCurrentPosition[1]);
            }
        });


        valueAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                //把执行动画的商品图片从父布局中移除
                shellLayout.removeView(animImg);
                //添加到购物车
                SaveShoppingCartRequest saveShoppingCartRequest = new SaveShoppingCartRequest();
                saveShoppingCartRequest.setConsumerId(mPresenter.getConsumer().getId());
                saveShoppingCartRequest.setGoodsId(goodsId);
                saveShoppingCartRequest.setCount("1");
                saveShoppingCartRequest.setAttachmentUrl("");
                mPresenter.addToShoppingCar(saveShoppingCartRequest);
            }
        });
        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.setDuration(1500);
        animatorSet.setInterpolator(new AccelerateInterpolator());
        animatorSet.playTogether(scaleXanim, scaleYanim, valueAnimator);
        animatorSet.start();
    }
}
